<?php

use Core\AdminController;
use Models\Config;
use Libraries\Uploader;

class SysController extends AdminController
{
	public function index()
	{
		$configs = Config::where('label', '充值设置')->get();

		$this->load->view('admin/sys/index', [
			'configs' => $configs,
		]);
	}

	public function add()
	{
		$this->load->library('form_validation');

		$this->form_validation->set_rules('label', '标签', 'required')
			->set_rules('name', '名称', 'required')
			->set_rules('value', '值', 'required');
		if (!$this->form_validation->run()) {
			return $this->load->view('admin/sys/add');
		}

		$config = new Config();
		$config->load($this->input->post());
		$config->add();

		return $this->success('添加成功');
	}

	public function edit($id)
	{
		$config = (new Config())->find($id);
		if (!$config) {
			show_404();
		}

		$this->load->library('form_validation');

		$this->form_validation->set_rules('label', '标签', 'required')
			->set_rules('name', '名称', 'required')
			->set_rules('value', '值', 'required');
		if (!$this->form_validation->run()) {
			return $this->load->view('admin/sys/edit', [
				'config' => $config
			]);
		}

		$config->load($this->input->post());
		$config->update();

		return $this->success('修改成功');
	}

	public function logo()
	{
		$logo = (new Config)->get_by_label('logo地址');
		if ($this->input->method() == 'post') {
			$value = $this->input->post('logo');
			$logo['value'] = $value;
			$logo->save();

			return $this->success('保存成功');
		}

		return $this->load->view('admin/sys/logo', [
			'logo' => $logo['value']
		]);
	}

	public function video()
	{
		$video = (new Config)->get_by_label('video地址');
		if ($this->input->method() == 'post') {
			$value = Uploader::image('video');
			if ($value) {
				$video['value'] = '/uploadfiles'.$value;
				$video->save();

				return $this->success('保存成功');
			} else {
				echo '<script>alert("保存失败");history.go(-1);</script>';
				exit;
			}



		}

		return $this->load->view('admin/sys/video', [
			'video' => $video['value']
		]);
	}

	public function email()
	{
		$configs = arr_key((new Config)->where('label', 'email')->get(), 'name');
		if ($this->input->method() == 'post') {
			foreach ($this->input->post() as $key => $value) {
				(new Config)->where([
					'label' => 'email',
					'name' => $key
					])->updateAll([
						'value' => $value
				]);
			}

			return $this->success('保存成功');
		}

		$this->load->view('admin/sys/email', [
			'configs' => $configs
		]);
	}

	public function delete($id)
	{
		$config = (new Config())->find($id);
		if (!$config) {
			show_404();
		}

		$config->delete();

		echo json_encode(['code' => 1]);
	}
}
